<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="千牛ID" prop="acookieId">
        <el-input v-model="queryParams.acookieId" placeholder="请输入千牛ID 或 线下订单" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="平台内部客服编号" prop="serviceCode">
        <el-input v-model="queryParams.serviceCode" placeholder="请输入平台内部客服编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创作者" prop="writerNickName">
        <el-input v-model="queryParams.writerNickName" placeholder="请输入创作者" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="结款日期" prop="settlementDate">
        <el-date-picker v-model="settlementDate" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="店铺" prop="storeCode">
        <el-select v-model="queryParams.storeCode" clearable placeholder="请选择">
          <el-option v-for="item in shops" :key="item.storeCode" :label="item.storeName" :value="item.storeCode">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否补单" prop="ifBrushing">
        <el-select v-model="queryParams.ifBrushing" clearable placeholder="请选择">
          <el-option label="补单" value="1"> </el-option>
          <el-option label="不补" value="2"> </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否报账" prop="checkSheet">
        <el-select v-model="queryParams.checkSheet" clearable placeholder="请选择">
          <el-option label="不报" value="4"> </el-option>
          <el-option label="报" value="1"> </el-option>
          <el-option label="未报" value="2"> </el-option>
          <el-option label="重复报账" value="3"> </el-option>
          <el-option label="无客服信息未报" value="5"> </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否结算" prop="ifBalance">
        <el-select v-model="queryParams.ifBalance" clearable placeholder="请选择">
          <el-option label="结算" value="1"> </el-option>
          <el-option label="未结" value="2"> </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="垫付审核" prop="ifAudit">
        <el-select v-model="queryParams.ifAudit" clearable placeholder="请选择">
          <el-option label="通过" value="1"> </el-option>
          <el-option label="拒绝" value="2"> </el-option>
          <el-option label="无需审核" value="3"> </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="结款月份" prop="settlementDate">
        <el-date-picker v-model="queryParams.settlementDate" type="month" value-format="yyyy-MM" placeholder="选择月">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="small" :disabled="multiple" @click="handleExport"
          v-hasPermi="['platform:order:export']">导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload" size="small" @click="handleImport"
          v-hasPermi="['platform:order:import']">客服数据导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload" size="small" @click="handleImportTB"
          v-hasPermi="['platform:order:qnImport']">千牛导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-upload" size="small" @click="handleImportRefund"
          v-hasPermi="['platform:order:refundImport']">售后退款导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload" size="small" @click="handleMakeOrder">批量修改补单</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain :disabled="multiple" size="small" @click="handleSettlement">批量修改结算</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row style="margin-bottom: 20px;">
      <el-tag> 店铺成交金额:{{ statistInfo.totalFlow }} </el-tag>
      <el-tag style="margin-left: 10px">
        平台抽点:{{ statistInfo.thirdParty }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        店铺收益:{{ statistInfo.platformProfit }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        客服收益:{{ statistInfo.supportStaffProfit }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        创作者收益:{{ statistInfo.writerProfit }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        退款金额:{{ statistInfo.refund }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        订单数:{{ statistInfo.totalOrder }}
      </el-tag>
    </el-row>
    <!-- 选中后统计 -->
    <el-row>
      <el-tag> 店铺成交金额:{{ selectionStatistInfo.totalFlow }} </el-tag>
      <el-tag style="margin-left: 10px">
        平台抽点:{{ selectionStatistInfo.thirdParty }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        店铺收益:{{ selectionStatistInfo.platformProfit }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        客服收益:{{ selectionStatistInfo.supportStaffProfit }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        创作者收益:{{ selectionStatistInfo.writerProfit }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        退款金额:{{ selectionStatistInfo.refund }}
      </el-tag>
      <el-tag style="margin-left: 10px">
        订单数:{{ selectionStatistInfo.totalOrder }}
      </el-tag>
    </el-row>
    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed="right" label="操作" width="150" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 当线下退款金额为0的时候，不显示 -->
          <div v-if="scope.row.offlineRefundAmount != 0">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['platform:order:edit']">线下退款审核</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="店铺" align="center" prop="storeName" />
      <el-table-column label="平台内部订单" align="center" prop="orderId" width="115" />
      <el-table-column label="千牛ID" align="center" prop="acookieId" width="115">


        <template slot-scope="scope">
          <el-image v-if="scope.row.picRrDic" style="width: 100px; height: 100px"
            :src="'data:image/jpeg;base64,' + scope.row.picRrDic"
            :preview-src-list="['data:image/jpeg;base64,' + scope.row.picRrDic]">
          </el-image>
          <span v-else>{{ scope.row.acookieId }}</span>

        </template>
      </el-table-column>
      <el-table-column label="买家ID" align="center" prop="buyerOpenUid" width="150" />
      <el-table-column label="平台内部客服编号" align="center" prop="serviceCode" />
      <el-table-column label="创作者" align="center" prop="writerNickName" width="120" />
      <el-table-column label="订单状态" :show-overflow-tooltip="true" align="center" prop="status">
        <template slot-scope="scope">
          {{ getLabelByValue(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="商品标题" :show-overflow-tooltip="true" align="center" prop="title" width="150" />
      <el-table-column label="预付金（元/￥）" align="center" prop="payment" />
      <el-table-column label="付款时间" align="center" prop="payTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应收款（元/￥）" align="center" prop="actualPayment" />
      <el-table-column label="放单价（元/￥）" align="center" prop="putPayment" />
      <!-- <el-table-column label="售中退款金额" align="center" prop="refund" /> -->
      <el-table-column label="退款金额" align="center" prop="afterRefund">
        <template slot-scope="scope">
          <span>{{ scope.row.afterRefund == 0 ? '' : scope.row.afterRefund }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客服垫付金额" align="center" prop="writerPaidPrice">
        <template slot-scope="scope">
          <span>{{ scope.row.writerPaidPrice == 0 ? '' : scope.row.writerPaidPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="写手已收定金" align="center" prop="depositReceived">
        <template slot-scope="scope">
          <span>{{ scope.row.depositReceived == 0 ? '' : scope.row.depositReceived }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线下退款金额" align="center" prop="offlineRefundAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.offlineRefundAmount == 0 ? '' : scope.row.offlineRefundAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否报账" align="center" prop="checkSheet" v-hasPermi="['platform:order:checkSheet']"
        width="150">
        <template slot-scope="scope">
          <!-- <el-switch v-if="(scope.row.status < 2 || scope.row.checkSheet == 2 || (scope.row.actualPayment - scope.row.refund) > 0 ) && scope.row.ifOpen == 2"
            :disabled="(scope.row.status != 2 || scope.row.ifBrushing == 1 || scope.row.ifBalance == 1) && scope.row.ifAudit == 1"
            v-model="scope.row.checkSheet"
            active-value="1"
            inactive-value="2"
            active-text="报"
            inactive-text="未报"
            @change="handleCheckSheetChange(scope.row)">
          </el-switch>
          <span v-else>{{ ['报账','未报','重复报账','不报'][parseInt(scope.row.checkSheet)-1] }}</span> -->
          <!-- {{ ['报账', '未报', '重复报账', '不报','无客服信息未报'][parseInt(scope.row.checkSheet) - 1] }} -->
          {{ !scope.row.serviceCode ? '无客服信息未报' : ['报账', '未报', '重复报账', '不报'][parseInt(scope.row.checkSheet) - 1] }}
          <!--          {{ ['报账','未报','重复报账','不报'][parseInt(scope.row.checkSheet)-1] }}-->
        </template>
      </el-table-column>
      <el-table-column label="是否结算" align="center" prop="ifBalance" v-hasPermi="['platform:order:ifBalance']"
        width="150">
        <template slot-scope="scope">
          <!-- <div v-if="scope.row.ifBrushing != 1"> -->
            <el-switch
              v-if="(scope.row.status == 2 && scope.row.ifBrushing == 2 || (scope.row.actualPayment - scope.row.refund) > 0) && scope.row.ifOpen == 2"
              :disabled="(scope.row.ifBrushing == 1 || scope.row.checkSheet != 1)" v-model="scope.row.ifBalance"
              active-value="1" inactive-value="2" active-text="结算" inactive-text="不结"
              @change="handleBalanceChange(scope.row)">
            </el-switch>
            <span v-else>{{ ['结算', '不结', '重复结算'][parseInt(scope.row.ifBalance) - 1] }}</span>
          <!-- </div>
<div v-else>不结</div> -->
        </template>
      </el-table-column>
      <el-table-column label="结算用户" align="center" prop="settle" width="200">
        <template slot-scope="scope">
          <!--          <el-checkbox-group :value="getSettleList(scope.row.settle)" @change="bindSettle">-->
          <!--            <el-checkbox v-for="(item,index) in settleList" :key="index" :label="item.id">{{item.name}}</el-checkbox>-->
          <!--          </el-checkbox-group>-->
          <!-- 当平台内部客服编号为null时或者补单按钮为1时(补单)，禁用结算用户 -->
          <el-select v-model="scope.row.settle" :disabled="scope.row.serviceCode == null || scope.row.ifBrushing == 1"
            multiple @change="bindSettle" @visible-change="bindSettleVisible($event, scope.row)" placeholder="请选择">
            <el-option v-for="item in settleList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="是否补单" align="center" prop="ifBrushing" width="150">
        <template slot-scope="scope">
          <el-switch v-if="scope.row.acookieId != '线下订单'" :disabled="scope.row.ifBalance == 1"
            v-model="scope.row.ifBrushing" active-color="#13ce66" inactive-color="#ff4949" active-value="1"
            inactive-value="2" active-text="补单" inactive-text="不补" v-hasPermi="['platform:order:ifBrushing']"
            @change="handleIfBrushingChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="垫付审核" align="center" prop="ifBalance" v-hasPermi="['platform:order:ifBalance']"
        width="150">
        <template slot-scope="scope">
          <!-- 当客服垫付金额为0的时候，不显示 当补单按钮为1时(不补)，禁用  :disabled="scope.row.ifBrushing == 1" -->
          <div v-if="scope.row.writerPaidPrice != 0">
            <el-switch v-if="scope.row.ifAudit != 3" v-model="scope.row.ifAudit" active-value="1" inactive-value="2"
              active-text="通过" inactive-text="拒绝" v-hasPermi="['platform:order:ifBrushing']"
              @change="handleifAuditChange(scope.row)">
            </el-switch>
            <span v-else>{{ ['通过', '拒绝', '无需审核'][parseInt(scope.row.ifAudit) - 1] }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="订单来源" align="center" prop="orderSource">
        <template slot-scope="scope">
          <!-- {{ orderSourceMap[scope.row.orderSource] }} -->
          {{ scope.row.orderSource }}
        </template>
      </el-table-column>
      <el-table-column label="绩效月份" align="center" prop="performance">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.performance, "{y}-{m}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结款日期" align="center" prop="settlementDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.settlementDate, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单导入日期" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易修改时间" align="center" prop="modified" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modified, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卖家备注内容" align="center" prop="sellerMemo" />
      <!-- <el-table-column
        label="结款备注"
        align="center"
        prop="settlementRemark"
      /> -->
      <el-table-column label="订单类型" align="center" prop="orderType" />
      <el-table-column label="备注" align="center" prop="remark" width="500" />
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改TB 订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="内部编号" prop="orderId">
          <el-input v-model="form.orderId" disabled />
        </el-form-item>

        <el-form-item label="千牛ID" prop="acookieId">
          <el-input v-model="form.acookieId" disabled />
        </el-form-item>

        <el-form-item label="买家ID" prop="buyerOpenUid">
          <el-input clearable v-model="form.buyerOpenUid" disabled placeholder="请输入买家ID" />
        </el-form-item>

        <el-form-item label="付款截图" prop="paymentScreenshot">
          <el-upload class="upload-demo" :action="uploadUrl" :headers="headers" :on-success="handleSuccess"
            :on-error="handleError" :before-upload="beforeUpload" :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              <div>只能上传jpg/png文件，且不超过500kb</div>
              <div style="color: #dc362e;">上传付款截图并提交表示线下退款审核通过</div>
            </div>
          </el-upload>
        </el-form-item>


        <el-form-item label="客服编号" prop="serviceCode">
          <el-input clearable v-model="form.serviceCode" disabled placeholder="请输入平台内部客服编号" />
        </el-form-item>

        <el-form-item label="客服垫付" prop="writerPaidPrice">
          <el-input clearable v-model="form.writerPaidPrice" disabled type="number" placeholder="如有垫付请输入垫付金额（￥）" />
        </el-form-item>

        <el-form-item label="创作者" prop="writerNickName">
          <el-input clearable v-model="form.writerNickName" disabled placeholder="请输入创作者" />
        </el-form-item>

        <el-form-item label="实收价" prop="actualPayment">
          <el-input clearable v-model="form.actualPayment" disabled type="number" placeholder="请输入实收价" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input clearable v-model="form.remark" disabled placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文档拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          > -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="qnUpload.title" :visible.sync="qnUpload.open" width="400px" append-to-body>
      <el-upload ref="qnUpload" :limit="1" accept=".xlsx, .xls" :headers="qnUpload.headers"
        :action="qnUpload.url + '?updateSupport=' + qnUpload.updateSupport" :disabled="qnUpload.isUploading"
        :on-progress="handleFileUploadProgressTB" :on-success="handleFileSuccessTB" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将 <b style="color:#fe5001">千牛</b> 文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileFormTB">确 定</el-button>
        <el-button @click="qnUpload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  editNew,
  getOrderStatistics,
  getOption,
  editBrushing,
  expenseAccount
} from "@/api/order";
import { getToken } from "@/utils/auth";
import editTableVue from '../../tool/gen/editTable.vue';

export default {
  name: "Order",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: { Authorization: "Bearer " + getToken() },
      fileList: [],
      options: [
        {
          label: "交易关闭",
          value: "1",
        },
        {
          label: "交易成功",
          value: "2",
        },
        {
          label: "买家已付款,等待卖家发货",
          value: "3",
        },
        {
          label: "卖家已发货，等待买家确认",
          value: "4",
        },
        {
          label: "未知状态",
          value: "5",
        },
      ],
      settlementDate: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // TB 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/order/batchImportClue",
        url: "",
      },
      // 千牛导入参数
      qnUpload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/order/tb/importTBOrder",
      },
      statistInfo: {
        totalFlow: "",
        thirdParty: "",
        platformProfit: "",
        supportStaffProfit: "",
        writerProfit: "",
        refund: "",
        totalOrder: "",
      },
      selectionStatistInfo: {
        totalFlow: 0,
        thirdParty: 0,
        platformProfit: 0,
        supportStaffProfit: 0,
        writerProfit: 0,
        refund: 0,
        totalOrder: 0,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        acookieId: null,
        buyerOpenUid: null,
        serviceCode: null,
        serviceName: null,
        writerId: null,
        writerNickName: null,
        writerName: null,
        tid: null,
        status: null,
        title: null,
        payment: null,
        payTime: null,
        endTime: null,
        modified: null,
        actualPayment: null,
        sellerMemo: null,
        account: null,
        checkSheet: "2",
        settlementDate: null,
        settlementRemark: null,
        performance: null,
        orderType: null,
        ifBalance: null,
        ifAudit: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      shops: [],
      orderSourceMap: {
        1: "淘宝",
        2: "天猫",
        3: "微信",
        4: "抖音",
        5: "拼多多",
        6: "对公",
        7: "线下",
        8: "内部",
        9: "其他渠道"
      },
      settleList: [
        { id: '0', name: '客服' },
        { id: '1', name: '写手' }
      ],
      settleIds: [],
      // 表格图片
      srcList: [],
      settlementId: [],
    };
  },
  created() {
    this.getList();
    this.getShops();
  },
  methods: {
    getSettleList(str) {
      if (str) {
        return str.split(',')
      }
      return [];
    },
    bindSettle(e) {
      this.settleIds = e;
    },
    bindSettleVisible(e, row) {
      let obj = row;
      if (!e) {
        obj.settle = this.settleIds.join(',');
        obj.orderSource = null;
        updateOrder(obj).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      }
    },

    // 列表是否报账滑块
    handleCheckSheetChange(row) {
      console.log(`Row acookieId: ${row.acookieId}, New checkSheet Value: ${row.checkSheet}`);
      const params = {
        orderId: row.orderId,
        acookieId: row.acookieId,
        checkSheet: row.checkSheet
      }
      this.edit(params);
    },
    // 列表是否结算滑块
    handleBalanceChange(row) {
      console.log(`Row acookieId: ${row.acookieId}, New ifBalance Value: ${row.ifBalance}`);
      const params = {
        orderId: row.orderId,
        acookieId: row.acookieId,
        ifBalance: row.ifBalance
      }
      this.edit(params);
    },
    // 列表是否刷单滑块
    handleIfBrushingChange(row) {
      console.log(`Row acookieId: ${row.acookieId}, New ifBrushing Value: ${row.ifBrushing}`);
      const params = {
        orderId: row.orderId,
        acookieId: row.acookieId,
        ifBalance: '2',
        checkSheet: '4',
        ifBrushing: row.ifBrushing
      }
      this.edit(params);
    },
    // 垫付审核滑块
    handleifAuditChange(row) {
      console.log(`Row acookieId: ${row.acookieId}, New ifBrushing Value: ${row.ifAudit}`);
      const params = {
        orderId: row.orderId,
        acookieId: row.acookieId,
        ifAudit: row.ifAudit,
        ifBalance: row.ifAudit
      }
      this.edit(params);
    },
    // 修改 是否（报账/刷单/结算）
    edit(params) {
      console.log("进入修改");
      editBrushing(params).then((res) => {
        this.$message({
          type: "success",
          message: `修改成功!`,
        });
        this.getList();
      })
    },
    // 修改是否刷单
    handleChange(row) {
      const params = {
        acookieId: row.acookieId,
        ifBrushing: row.ifBrushing === "1" ? "1" : "2",
      };
      console.log(`Row ID: ${row.orderId}, New Value: ${row.ifBrushing}`);
      this.$confirm(
        `此操作将该订单改为 ${row.ifBrushing === "1" ? "非刷单" : "刷单"}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        editBrushing(params).then((res) => {
          this.$message({
            type: "success",
            message: `修改成功!`,
            // message: `${row.ifBrushing === 1 ? "非刷单" : "刷单"}成功!`,
          });
          this.getList();
        });
      })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },

    getLabelByValue(value) {
      const option = this.options.find(option => option.value === value);
      return option ? option.label : "未知状态";
    },

    /** 查询订单列表 */
    getList() {
      this.loading = true;
      if (this.settlementDate) {
        this.queryParams.settlementStaTime = this.settlementDate[0]
          ? this.settlementDate[0]
          : "";
        this.queryParams.settlementEndTime = this.settlementDate[1]
          ? this.settlementDate[1]
          : "";
      }

      listOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;

        this.orderList.forEach((item) => {
          item.settle = this.getSettleList(item.settle);
        })
        this.total = response.total;
        this.loading = false;
      });
      this.getStatistics();
    },
    getShops() {
      getOption().then((response) => {
        this.shops = response.data;
      });
    },
    getStatistics() {
      const query = {
        acookieId: this.queryParams.acookieId,
        serviceCode: this.queryParams.serviceCode,
        writerNickName: this.queryParams.writerNickName,
        status: this.queryParams.status,
        settlementStaTime: this.queryParams.settlementStaTime,
        settlementEndTime: this.queryParams.settlementEndTime,
        orderSource: this.queryParams.orderSource,
        ifBrushing: this.queryParams.ifBrushing,
        storeCode: this.queryParams.storeCode,
        checkSheet: this.queryParams.checkSheet,
        ifBalance: this.queryParams.ifBalance,
        ifAudit: this.queryParams.ifAudit,
      }
      getOrderStatistics(query).then((response) => {
        console.log(response, "res");
        this.statistInfo = response.data;
      });
    },
    getSelectionStatistics() {
      const query1 = {
        orderIdStr: this.ids.join()
      }
      getOrderStatistics(query1).then((response) => {
        this.selectionStatistInfo = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        acookieId: null,
        buyerOpenUid: null,
        serviceCode: null,
        serviceName: null,
        writerId: null,
        writerNickName: null,
        writerName: null,
        tid: null,
        status: null,
        title: null,
        payment: null,
        payTime: null,
        endTime: null,
        modified: null,
        actualPayment: null,
        sellerMemo: null,
        account: null,
        checkSheet: null,
        settlementDate: [],
        settlementRemark: null,
        performance: null,
        orderType: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        ifBrushing: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.settlementDate = [];

      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId);
      this.settlementId = selection.filter((el) => el.serviceCode && el.checkSheet == 1 && el.ifBalance == 2).map(person => person.orderId);
      console.log(this.settlementId, 'this.settlementId');

      console.log("选中列表：" + this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.getStatistics();
      if (this.ids.length) {
        this.getSelectionStatistics();
      } else {
        this.selectionStatistInfo = {
          totalFlow: 0,
          thirdParty: 0,
          platformProfit: 0,
          supportStaffProfit: 0,
          writerProfit: 0,
          refund: 0,
          totalOrder: 0,
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId;
      getOrder(orderId).then((response) => {
        if (response.data.paymentScreenshot) {
          this.fileList = response.data.paymentScreenshot.split(',').map(el => {
            const lastIndex = el.lastIndexOf('/');
            return {
              name: lastIndex !== -1 ? el.slice(lastIndex + 1) : el,
              url: process.env.VUE_APP_BASE_API + el,
            }
          })
        }

        this.form = response.data;
        this.open = true;
        this.title = "线下退款审核";
      });
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 淘宝文件上传中处理
    handleFileUploadProgressTB(event, file, fileList) {
      this.qnUpload.isUploading = true;
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "客服数据导入";
      this.upload.open = true;
      this.upload.url = process.env.VUE_APP_BASE_API + "/system/XsSController/batchImportClue";
    },

    handleImportTB() {
      this.qnUpload.title = "千牛文档导入";
      this.qnUpload.open = true;
    },

    handleImportRefund() {
      this.upload.title = "退款文档导入";
      this.upload.open = true;
      this.upload.url = process.env.VUE_APP_BASE_API + "/system/order/refund/importRefundOrder";
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },

    // 淘宝文件上传成功处理
    handleFileSuccessTB(response, file, fileList) {
      this.qnUpload.open = false;
      this.qnUpload.isUploading = false;
      this.$refs.qnUpload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 提交上传文件
    submitFileFormTB() {
      this.$refs.qnUpload.submit();
    },

    /** 下载模板操作 */
    importTemplate() {
      location.href =
        "https://www.sczyjk.top/prod-api/profile/upload/importmodel/储蓄卡导入模板.xlsx";
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            editNew(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除TB 订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log( this.ids, " this.ids");
      this.download(
        "system/order/export",
        {
          ...this.queryParams,
          orderIdList:this.ids.join(','),
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功', response);
      this.form.paymentScreenshot = response.fileName
    },
    handleError(error, file, fileList) {
      console.log('上传失败', error);
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    },
    //行标红
    tableRowClassName({ row, rowIndex }) {
      console.log(row.checkSheet, !row.serviceCode, row.serviceCode, 'row.serviceCode');

      // 这里假设年龄大于 25 的行需要标红
      if (row.checkSheet == 4 || !row.serviceCode) {
        return 'highlight-row';
      }
      return '';
    },
    //批量修改结算
    handleSettlement() {
      expenseAccount(this.ids).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: `修改成功!`,
          });
          this.getList();
        }
      })
    },
    //批量修改补单
    handleMakeOrder() {
      this.upload.title = "批量修改补单";
      this.upload.open = true;
      this.upload.url = process.env.VUE_APP_BASE_API + "/system/XsSController/replenishment";
    },
  },
};
</script>
<style scoped>
::v-deep .highlight-row {
  background-color: #ff000033;
  /* 半透明红色背景 */
  /*  color: red; 文字颜色为红色 */
}
</style>
